package com.yarolegovich.lovelydialog;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.app.Context;
import ohos.utils.PacMap;

/**
 * Created by yarolegovich on 16.04.2016.
 */
public class LovelyCustomDialog extends AbsLovelyDialog<LovelyCustomDialog> {
    private Component addedView;
    private InstanceStateManager instanceStateManager;

    public LovelyCustomDialog(Context context) {
        super(context);
    }

    public LovelyCustomDialog(Context context, int theme) {
        super(context, theme);
    }

    public LovelyCustomDialog setView(int layout) {
        LayoutScatter inflater = LayoutScatter.getInstance(getContext());
        ComponentContainer parent = findView(ResourceTable.Id_custom_view_container);
        addedView = inflater.parse(layout, parent, true);
        return this;
    }

    public LovelyCustomDialog setView(Component customView) {
        ComponentContainer container = findView(ResourceTable.Id_custom_view_container);
        container.addComponent(customView);
        addedView = customView;
        return this;
    }

    public LovelyCustomDialog configureView(ViewConfigurator<Component> configurator) {
        if (addedView == null) {
            throw new IllegalStateException(string(ResourceTable.String_ex_msg_dialog_view_not_set));
        }
        configurator.configureView(addedView);
        return this;
    }

    public LovelyCustomDialog setListener(int viewId, Component.ClickedListener listener) {
        return setListener(viewId, false, listener);
    }

    public LovelyCustomDialog setListener(int viewId, boolean dismissOnClick, Component.ClickedListener listener) {
        if (addedView == null) {
            throw new IllegalStateException(string(ResourceTable.String_ex_msg_dialog_view_not_set));
        }
        Component.ClickedListener clickListener = new ClickListenerDecorator(listener, dismissOnClick);
        findView(viewId).setClickedListener(clickListener);
        return this;
    }

    public LovelyCustomDialog setInstanceStateManager(InstanceStateManager instanceStateManager) {
        this.instanceStateManager = instanceStateManager;
        return this;
    }

    @Override
    void onSaveInstanceState(PacMap outState) {
        super.onSaveInstanceState(outState);
        instanceStateManager.saveInstanceState(outState);
    }

    @Override
    void restoreState(PacMap savedState) {
        super.restoreState(savedState);
        instanceStateManager.restoreInstanceState(savedState);
    }

    @Override
    protected int getLayout() {
        return ResourceTable.Layout_dialog_custom;
    }


    public interface InstanceStateManager {
        void saveInstanceState(PacMap outState);

        void restoreInstanceState(PacMap savedState);
    }
}
